#!/usr/bin/python
import unittest
import tempfile
import sys
import os
from StringIO import StringIO

# Import app modules
tests_dir = os.path.dirname(sys.argv[0])
from uya.routerconf import interfaces

import common

expected_interfaces = {
    'bridging': {
        'br0': {
            'state': False, 
            'method': 'static', 
            'interface_netmask': '255.255.255.128', 
            'bridge_stp': 'on', 
            'bridge_maxwait': '10', 
            'bridge_ports': 'eth0 ath0', 
            'interface_address': '192.168.3.1'
        }
    },
    'ethernet': {
        'eth0': {
            'state': True, 
            'method': 'dhcp',
            'interface_address': '192.168.1.20',
        },
        'eth1': {
            'state': True,
            'method': 'static', 
            'interface_netmask': '255.255.255.0', 
            'interface_address': '192.168.1.3',
        }, 
    },
    'wireless': {
        'ath0': {
            'state': False, 
            'method': 'static', 
            'madwifi_type': 'sta',
            'interface_netmask': '255.255.255.0', 
            'interface_address': '192.1.1.1', 
            'madwifi_security': 'wpa2-psk', 
            'madwifi_wpa_passphrase': '12345ABCDE12345ABCDE'
        }
    }
}
 
class TestNetworkInterfaces(unittest.TestCase, common.BaseTestConfig):        

    root_tests_dir = tests_dir

    def setUp(self):
        def fake_get_system_interface(procfile=None):
            return ["eth0", "eth1", "wifi0", "lo"]
        interfaces.get_system_interfaces = fake_get_system_interface 
                
    def test_network_interfaces(self):
        def callback(config): 
            return interfaces.network_interfaces(config["interfaces"], 
               config["routes"])
        expected_modified_filenames = [
            '/etc/network/interfaces',
            '/etc/hostapd/hostapd-ath1.conf',
            '/etc/wpa_supplicant/wpasupplicant-ath2.conf',
            ]  
        self.compare_filesystems(expected_modified_filenames, 
            [['/etc/init.d/networking', 'restart'],
             ['/etc/init.d/quagga', 'restart']], callback)

    def test_network_interfaces_get(self):
        config = common.init_filesystems_for_get(tests_dir)
        cinterfaces = config["interfaces"]
        interfaces.network_interfaces_get(cinterfaces)
        self.assertEqual(expected_interfaces["bridging"], cinterfaces["bridging"])
        self.assertEqual(expected_interfaces["ethernet"], cinterfaces["ethernet"])
        self.assertEqual(expected_interfaces["wireless"], cinterfaces["wireless"])
        
def suite():
    return unittest.TestLoader().loadTestsFromTestCase(TestNetworkInterfaces)
                
if __name__ == '__main__':
    unittest.main()
